# encoding:utf-8
import requests
import json
import base64
import os

# client_id 为官网获取的AK， client_secret 为官网获取的SK
AK = 'V88Fk0Sc8aCve8s3UoVwkXab'
SK = 'QTa6PlGlAG9z9n8AjvxyMeB4loFxeQ33'
null = ''


def get_token():
    url = 'https://aip.baidubce.com/oauth/2.0/token'
    data = {}
    data['grant_type'] = 'client_credentials'
    data['client_id'] = AK
    data['client_secret'] = SK
    response = requests.post(url, data)
    content = response.content.decode('utf-8')
    content = json.loads(content)
    print('access_token:\t', content['access_token'])
    return content['access_token']


def base666(image):
    f1 = open(image, 'rb')
    f1_64 = base64.b64encode(f1.read())
    f1.close()
    f1_64 = f1_64.decode()
    return f1_64


def edittattr(face1, image):
    global null
    url = 'https://aip.baidubce.com/rest/2.0/face/v1/editattr' + \
          "?access_token=" + get_token()
    # action_type
    # TO_KID: 变小孩
    # TO_OLD: 变老人
    # TO_FEMALE: 变女生
    # TO_MALE: 变男生
    data =  {"image": base666(face1), "image_type": 'BASE64',"action_type": "TO_MALE", }
    data = json.dumps(data)
    headers = {'content-type': 'application/json'}
    response = requests.post(url, data, headers=headers)
    # print(response.content)
    req_con1 = response.content.decode('utf-8')
    content = eval(req_con1)
    # print(content)
    result1 = content['result']
    result = result1['image']
    imgdata = base64.b64decode(result)
    with open(image, 'wb') as fp:
        fp.write(imgdata)
        fp.close()

if __name__ == '__main__':
    image1 = './face_distinct.jpg'
    image = './face5.jpg'
    edittattr(image1, image)